package com.simple.sso.client.filter;

import com.simple.sso.client.utils.HttpUtils;
import com.simple.sso.client.utils.SessionStorage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@WebFilter(filterName = "logoutFilter", urlPatterns = "/*")
public class LogoutFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("logoutFilter filter init method...");
        config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException { System.out.println("logoutFilter filter doFilter method...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        String clientIndexUri = config.getInitParameter("clientIndexUri");
        String logoutUrl = config.getInitParameter("logoutUrl");
        String token = (String) session.getAttribute("token");
        String uri = request.getRequestURI();

        if (uri.contains(".js")) {
            chain.doFilter(request, response);
            return;
        }

        //子系统进行登出请求，则向认证中心发送注销请求
        if (uri.contains("/logout")) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("logoutRequest", token);
            HttpUtils.post(logoutUrl, paramMap);

            session = SessionStorage.INSTANCE.removeAndGetSession(token);
            if (session != null) {
                session.invalidate();
                System.out.println("------>>>局部session失效成功！");
            }

            response.sendRedirect(clientIndexUri);
            return;
        }

        //子系统被动注销，即认证系统主动发起注销（链接带有logoutRequest参数信息，参数值为token）
        token = request.getParameter("logoutRequest");
        if (!StringUtils.isEmpty(token)) {
            session = SessionStorage.INSTANCE.removeAndGetSession(token);
            if (session != null) {
                session.invalidate();
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("logoutFilter filter destroy method...");
    }
}
